package com.example.www.Controller;

import com.example.www.Base.Result;
import com.example.www.Entity.Video;
import com.example.www.Service.VideoService;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RestController
public class VideoController {

    @Value("${qiniu.accesskey}")
    private String accessKey;

    @Value("${qiniu.secretkey}")
    private String secretKey;

    @Value("${qiniu.bucketname}")
    private String bucket;

    @Value("${qiniu.url}")
    private String qiniuUrl;


    @Autowired
    private VideoService videoService;

    @GetMapping("/api/videolist")
    @CrossOrigin
    public Result getVideoList(){
        return Result.videos(videoService.getVideoCoversList());
    }

    @GetMapping("/api/video")
    @CrossOrigin
    public Result getVideo(@RequestParam("id") int id){
        return Result.video(videoService.getVideoLink(id));
    }
    @PostMapping("/api/addvideo")
    @CrossOrigin
    public Result addVideo(@RequestParam("title") String title,
                           @RequestParam("cover") String cover,
                           @RequestParam("video") String video){
        videoService.addVideo(title,cover,video);
        return Result.OK();
    }

    @DeleteMapping("/api/deletevideo")
    @CrossOrigin
    public Result deleteVideo(@RequestParam("id") int id) {
        Video video = videoService.getVideo(id);
        if(video!=null) {
            String key = video.getLink().substring(qiniuUrl.length());
            String coverKey = video.getImage().substring(qiniuUrl.length());
            Configuration cfg = new Configuration(Region.region0());
            Auth auth = Auth.create(accessKey, secretKey);
            BucketManager bucketManager = new BucketManager(auth, cfg);
            try {
                bucketManager.delete(bucket, key);
                bucketManager.delete(bucket, coverKey);
            } catch (QiniuException ex) {
                System.err.println(ex.code());
                System.err.println(ex.response.toString());
                return Result.internalError();
            }
            videoService.deleteVideo(id);
            return Result.OK();
        }else {
            return Result.OK();
        }
    }
}
